<?php
namespace addons\user\controller;


use app\common\Code;
use app\common\model\Contact;
use app\common\model\Order;
use app\common\model\Trade;
use app\common\OrderStatus;
use app\common\Session;
use think\addons\Controller;

class App extends Controller
{
    /**
     * 联系我们
     * 必要参数：
     * message 内容
     * community_id 社区id
     * 非必要参数
     * title 标题
     */
    public function contact_us()
    {
        $param = input();
        $user = Session::get_local_user();
        if (!$user)  #用户没有登录
        {
            response_json(Code::NO_SELLER);
        }
        $param['user_id'] = $user->id;
        $result = $this->validate(
            $param,
            [
                'message' => 'require',             #联系我们内容
                'community_id' => 'require|number', #用户所在社区
            ]);
        if (true !== $result) {
            response_json(Code::PARAM_ERROR);
        }
        Contact::add_contact($param);
        response_json(Code::NONE);
    }

    /**
     * 取消订单
     * 参数 order_id
     */
    public function cancel_order()
    {
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $order_id = input('order_id');
        /** @var  Order $order */
        $order = Order::get(["order_id" => $order_id]);
        if (empty($order)) {
            response_json(Code::ORDER_EMPTY);
        }
        if ($order->order_status_id >= OrderStatus::YIJIEDAI) {
            response_json(Code::ORDER_YIJIEDAN);
        }
        if ($order->order_status_id == OrderStatus::YIZHIFU) {
            $money = $order->total;// 待退款金额
            Trade::create_cancel_order(
                sprintf("%s%s%s", "cancelorder", time(), rand(1000, 9999)),
                $money,
                sprintf("订单%s 已被取消，系统将订单金额%s转入到您的余额", $order_id, $money)
            );
            $fund = $user->getUserFund();
            $fund->setInc("value", abs($money));
        }
        $order->delete();
        response_json(Code::NONE);
    }


}